package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.Collection;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.RequestDao;
import ar.com.ford.it.fullEconomics.persistence.dao.RequestItemDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr01Request;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr02Requestitm;
import ar.com.ford.it.fullEconomics.struct.RequestFindStruct;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class RequestLogic {

    private static final String CLASS_NAME = CommodityLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * crea el request pasado por parametro
     * 
     * @param req
     * @param user
     * @return
     * @throws FullEconomicsException
     */
    public Teesr01Request createRequest(Teesr01Request req,
                                        FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createRequest";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestDao dao = new RequestDao();
        String[] fields = new String[1];
        Object[] values = new Object[1];

        try {
            PersistenceUtil.newTransaction();
            fields[0] = "eesr01PlantCodeC";
            values[0] = user.getTeesg01Plant();
            Integer lastCode = dao.getMax(new Teesr01Request(), fields, values,
                    "eesr01RequestNumberK");
            req.setEesr01PlantCodeC(user.getTeesg01Plant());
            req.setEesr01RequestNumberK(lastCode + 1);
            req.setEesr01CreateUserC(user.getId());
            req.setEesr01LastUpdtUserC(user.getId());
            req.setEesr01CreateS(new Timestamp(System.currentTimeMillis()));
            req.setEesr01LastUpdtS(new Timestamp(System.currentTimeMillis()));
            dao.createRequest(req);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Request Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Request.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return req;
    }

    /**
     * cierra el request pasado por parametro
     * 
     * @param code
     * @param user
     * @throws FullEconomicsException
     */
    public void closeRequest(Integer code, FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "closeRequest";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestDao dao = new RequestDao();
        Teesr01Request workingCopy = null;

        try {
            PersistenceUtil.newTransaction();
            workingCopy = dao.getRequestForUpdate(code, user.getTeesg01Plant());
            workingCopy.setEesr01RequestStatusCodeC("C");
            workingCopy.setEesr01RequestClosureS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEesr01RequestClosureUserC(user.getId());
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Close Request Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Request.CLOSE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }
    
    /**
     * cierra el request pasado por parametro
     * 
     * @param code
     * @param user
     * @throws FullEconomicsException
     */
    public void reopenRequest(Integer code, FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "closeRequest";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestDao dao = new RequestDao();
        Teesr01Request workingCopy = null;

        try {
            PersistenceUtil.newTransaction();
            workingCopy = dao.getRequestForUpdate(code, user.getTeesg01Plant());
            workingCopy.setEesr01RequestStatusCodeC("I");
            workingCopy.setEesr01RequestClosureS(null);
            workingCopy.setEesr01RequestClosureUserC(null);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Close Request Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Request.CLOSE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * guarda los cambios hechos en el request pasado por parametro
     * 
     * @param req
     * @param user
     * @throws FullEconomicsException
     */
    public void updateRequest(Teesr01Request req, FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "updateRequest";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestDao dao = new RequestDao();
        Teesr01Request workingCopy = null;

        try {
            PersistenceUtil.newTransaction();
            PersistenceUtil.getPersistenceManager().clearCache();
            workingCopy = dao.getRequestForUpdate(
                    req.getEesr01RequestNumberK(), user.getTeesg01Plant());

            workingCopy.setEesr01RequestIssueDateY(req
                    .getEesr01RequestIssueDateY());
            workingCopy.setEesr01RequestContactNameN(req
                    .getEesr01RequestContactNameN());
            workingCopy.setEesr01RequestCommentsX(req.getEesr01RequestCommentsX());
            workingCopy.setEesr01LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEesr01LastUpdtUserC(user.getId());
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Request item Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Request.UPDATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * elimina el request pasado por parametro
     * @param req
     * @throws FullEconomicsException
     */
    public void deleteRequest(Teesr01Request req) throws FullEconomicsException {

        String METHOD_NAME = "deleteRequest";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestDao dao = new RequestDao();
        RequestItemDao itemDao = new RequestItemDao();
        RequestItemLogic itemLogic = new RequestItemLogic();
        Collection<Teesr02Requestitm> items = itemLogic.findRequestItems(req);
        try {
            PersistenceUtil.newTransaction();
            for(Teesr02Requestitm item : items){
                itemDao.deleteRequestItem(item);
            }
            dao.deleteRequest(req);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "delete Request item Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Request.DELETE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * busca todos los request que cumplan con con lo especificado por el filtro
     * 
     * @param findStruct
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr01Request> findRequests(RequestFindStruct findStruct)
            throws FullEconomicsException {

        String METHOD_NAME = "findRequests";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestDao dao = new RequestDao();
        Collection<Teesr01Request> ret;
        try {
            ret = dao.findRequests(findStruct);
        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Requests Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Request.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return ret;
    }

}
